const app = getApp();
const api = app.globalData.api;
Page({
  data: {
    imageJsonList: [],//临时用于浏览的图片和用于上传到后台的图片地址
    userInfo: {},
    dynamic: {
      uid: 0,//当前用户id
      content: '',//文字内容
      imgUrls: [],
    },
  },

  onShow() {
    this.setData({
      'userInfo': wx.getStorageSync('loginUser')
    })
  },

  //同步书写的文字内容
  inputContent(e) {
    this.setData({
      'dynamic.content': e.detail.value
    });
    console.log(this.data.dynamic.content);
  },

  chooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 9 - this.data.imageJsonList.length, // 最多可选择的文件数量
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFiles = res.tempFiles;
        console.log(tempFiles);
        let tempImageJsonList = that.data.imageJsonList;//临时imageJsonList
        tempFiles.forEach((item) => {
          tempImageJsonList.push(item.tempFilePath);//用于浏览与上传
        });
        that.setData({
          'imageJsonList': tempImageJsonList//用于上传
        });
      },
      fail: function () {
        //未选择图片
        wx.showToast({
          title: '未上传图片',
          icon: 'error'
        });
      }
    });
  },

  deleteImage: function (e) {
    const index = e.currentTarget.dataset.index;//获取要删除的照片的索引
    let tempImageList = this.data.imageJsonList;
    tempImageList.splice(index, 1);
    this.setData({
      'imageJsonList': tempImageList//删除
    });
  },

  uploadDynamic() {
    wx.request({
      url: api + '/user/addOneDynamic',
      method: 'POST',
      data: this.data.dynamic,
      success: (res) => {
        console.log(res.data);
        //成功
        if (res.data.code == 200) {
          wx.showToast({
            title: '动态上传成功',
            icon: 'success',
          });
          //0.2秒后跳转到动态圈子
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/translationCircle/translationCircle',
            });
          }, 200);
        } else {
          wx.showToast({
            title: '动态发布出现异常',
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        console.log(err);
        wx.showToast({
          title: '动态发布请求出错',
          icon: 'none',
        });
      }
    })
  },

  //发布动态
  fabuDynamic: function () {
    //整理一下上传的动态数据
    //1、判断内容和图片是否都为空
    if (!this.data.dynamic.content && this.data.dynamic.imgUrls.length == 0) {
      wx.showToast({
        title: '发布的动态不能为空',
        icon: 'none'
      });
      return;
    }
    //2、设置uid
    this.setData({
      'dynamic.uid': this.data.userInfo.id
    });
    //先上传图片
    //对每个图片数据循环进行上传
    let imageJsonList = this.data.imageJsonList;
    let tempDynamic = this.data.dynamic;
    let uploadTasks = [];
    let tempImgUrlList = [];
    let tempUser = this.data.userInfo;
    //一个一个上传
    imageJsonList.forEach((item) => {
      // 上传背景图片到后端保存
      let uploadTask = wx.uploadFile({
        url: api + '/user/uploadBgImg',
        filePath: item,
        name: 'file',
        header: { 'Content-Type': 'multipart/form-data' },
        formData: {
          'id': tempUser.id,
        },
        success: function (res) {
          var resData = JSON.parse(res.data);//wx.uploadFile回调函数返回的值是字符串，要先转为json数据
          if (resData.code == 200) {
            // 上传成功
            let img = (resData.data.url);
            tempImgUrlList.push(img);
          } else {
            wx.showToast({
              title: resData.desc,
              icon: 'none',
            })
          }
        },
        fail: function (err) {
          // 上传失败
          console.error('上传失败', err);
          wx.showToast({
            title: '图片上传出现异常',
            icon: 'none',
          });
        }
      });
      uploadTasks.push(uploadTask);
    });
    setTimeout(() => {
      tempDynamic.imgUrls = tempImgUrlList;
      this.setData({
        'dynamic': tempDynamic
      });
      console.log("此时dynamic==>", this.data.dynamic);
      //等待所有图片上传完成
      Promise.all(uploadTasks).then(() => {
        setTimeout(() => {//延时0.3秒再执行修改的方法
          //上传图片后，开始上传动态
          this.uploadDynamic();
        }, 300); // 300毫秒等于0.3秒
      });
    }, 1000)
  },
})